// 重新设计的聚合逻辑
// 数据流：Raw Data → Daily → Monthly → Yearly
// 保留策略：Daily(1天) → Monthly(30天) → Yearly(12个月)

// 常量定义
var DAILY_RETENTION_DAYS = 1;     // Daily只保留当天
var MONTHLY_RETENTION_DAYS = 30;  // Monthly保留30天（关键！）
var YEARLY_RETENTION_MONTHS = 12; // Yearly保留12个月

// 动态时间戳生成函数
function getCurrentTimestamp() {
    return new Date();
}

// 调试函数
function debugLog(msg, data) {
    if (data === undefined) {
        node.warn(`DEBUG - ${msg}`);
    } else {
        node.warn(`DEBUG - ${msg}: ${JSON.stringify(data, null, 2)}`);
    }
}

// 计算电表能耗
function calculateConsumption(history) {
    if (!history || history.length < 2) {
        const singleRecord = history && history.length === 1 ? history[0] : null;
        return {
            consumption: 0,
            startValue: singleRecord ? singleRecord.value : 0,
            endValue: singleRecord ? singleRecord.value : 0,
            startTime: singleRecord ? singleRecord.timestamp : null,
            endTime: singleRecord ? singleRecord.timestamp : null
        };
    }

    // 按时间排序
    const sortedHistory = [...history].sort((a, b) => 
        new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime()
    );

    const firstReading = sortedHistory[0];
    const lastReading = sortedHistory[sortedHistory.length - 1];

    return {
        consumption: Number((lastReading.value - firstReading.value).toFixed(2)),
        startValue: Number(firstReading.value.toFixed(2)),
        endValue: Number(lastReading.value.toFixed(2)),
        startTime: firstReading.timestamp,
        endTime: lastReading.timestamp
    };
}

// 计算滚动窗口消耗（基于Daily数据）
function calculateRollingWindowFromDaily(stats, pointId, windowDays, currentDate) {
    const allDataPoints = [];
    
    // 收集指定天数内的所有Daily数据
    for (let i = windowDays - 1; i >= 0; i--) {
        const date = new Date(currentDate);
        date.setDate(date.getDate() - i);
        const dayKey = formatDate(date);
        
        if (stats.byTimeDimension.daily[dayKey] && stats.byTimeDimension.daily[dayKey][pointId]) {
            const dayData = stats.byTimeDimension.daily[dayKey][pointId];
            if (dayData.startTime && dayData.endTime) {
                allDataPoints.push({
                    value: dayData.startValue,
                    timestamp: dayData.startTime
                });
                allDataPoints.push({
                    value: dayData.endValue,
                    timestamp: dayData.endTime
                });
            }
        }
    }
    
    if (allDataPoints.length === 0) {
        return {
            consumption: 0,
            startValue: 0,
            endValue: 0,
            startTime: null,
            endTime: null
        };
    }
    
    // 按时间排序
    allDataPoints.sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
    
    // 计算最小值和最大值
    const minValue = Math.min(...allDataPoints.map(p => p.value));
    const maxValue = Math.max(...allDataPoints.map(p => p.value));
    
    const minPoint = allDataPoints.find(p => p.value === minValue);
    const maxPoint = allDataPoints.find(p => p.value === maxValue);
    
    return {
        consumption: Number((maxValue - minValue).toFixed(2)),
        startValue: Number(minValue.toFixed(2)),
        endValue: Number(maxValue.toFixed(2)),
        startTime: minPoint.timestamp,
        endTime: maxPoint.timestamp
    };
}

// 计算月度汇总（基于Monthly数据）
function calculateMonthlyAggregationFromMonthly(stats, pointId, targetMonth, currentDate) {
    const monthlyDimension = stats.byTimeDimension.monthly;
    const allDataPoints = [];
    
    debugLog(`Calculating monthly aggregation for ${pointId} in ${targetMonth}`, {
        availableMonthlyKeys: Object.keys(monthlyDimension),
        targetMonth: targetMonth
    });
    
    // 收集该月份的所有Monthly数据
    Object.keys(monthlyDimension).forEach(dayKey => {
        if (dayKey.startsWith(targetMonth)) {
            if (monthlyDimension[dayKey] && monthlyDimension[dayKey][pointId]) {
                const monthlyData = monthlyDimension[dayKey][pointId];
                debugLog(`Found monthly data for ${dayKey}`, monthlyData);
                
                if (monthlyData.startTime && monthlyData.endTime) {
                    allDataPoints.push({
                        value: monthlyData.startValue,
                        timestamp: monthlyData.startTime
                    });
                    allDataPoints.push({
                        value: monthlyData.endValue,
                        timestamp: monthlyData.endTime
                    });
                }
            }
        }
    });
    
    debugLog(`Monthly aggregation data collection for ${targetMonth}`, {
        dataPointsFound: allDataPoints.length,
        allDataPoints: allDataPoints
    });
    
    if (allDataPoints.length === 0) {
        return {
            consumption: 0,
            startValue: 0,
            endValue: 0,
            startTime: null,
            endTime: null,
            daysWithData: 0
        };
    }
    
    // 按时间排序
    allDataPoints.sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
    
    // 计算最小值和最大值
    const minValue = Math.min(...allDataPoints.map(p => p.value));
    const maxValue = Math.max(...allDataPoints.map(p => p.value));
    
    const minPoint = allDataPoints.find(p => p.value === minValue);
    const maxPoint = allDataPoints.find(p => p.value === maxValue);
    
    // 计算该月有数据的天数
    const daysWithData = new Set(allDataPoints.map(p => p.timestamp.slice(0, 10))).size;
    
    const result = {
        consumption: Number((maxValue - minValue).toFixed(2)),
        startValue: Number(minValue.toFixed(2)),
        endValue: Number(maxValue.toFixed(2)),
        startTime: minPoint.timestamp,
        endTime: maxPoint.timestamp,
        daysWithData: daysWithData
    };
    
    debugLog(`Monthly aggregation result for ${pointId} in ${targetMonth}`, result);
    return result;
}

// 工具函数
function formatDate(date) {
    return date.toISOString().slice(0, 10);
}

function formatMonth(date) {
    return date.toISOString().slice(0, 7);
}

function getLast12Months(currentDate) {
    const months = [];
    for (let i = 11; i >= 0; i--) {
        const date = new Date(currentDate);
        date.setMonth(date.getMonth() - i);
        months.push(formatMonth(date));
    }
    return months;
}

try {
    // 主聚合流程
    var currentDate = getCurrentTimestamp();
    var stats = global.get('_ELECTRIC_STATISTICS_') || { 
        byMeasurementPoint: {},
        byTimeDimension: {
            daily: {},
            weekly: {},
            monthly: {},
            yearly: {}
        },
        lastUpdated: null
    };
    
    var currentDay = formatDate(currentDate);
    var currentMonth = formatMonth(currentDate);

    debugLog('Starting redesigned aggregation', {
        currentDay: currentDay,
        currentMonth: currentMonth,
        existingDailyKeys: Object.keys(stats.byTimeDimension.daily || {}),
        existingMonthlyKeys: Object.keys(stats.byTimeDimension.monthly || {}),
        existingYearlyKeys: Object.keys(stats.byTimeDimension.yearly || {})
    });

    // 检查是否有当天的数据收集
    const hasCurrentDayData = Object.keys(stats.byMeasurementPoint || {}).some(pointId => {
        const pointData = stats.byMeasurementPoint[pointId];
        return pointData && pointData.history && pointData.history.some(record => 
            record.timestamp.startsWith(currentDay)
        );
    });

    // 获取所有测点ID
    const allPointIds = new Set();
    Object.keys(stats.byMeasurementPoint || {}).forEach(pointId => allPointIds.add(pointId));
    Object.keys(stats.byTimeDimension.daily || {}).forEach(dayKey => {
        Object.keys(stats.byTimeDimension.daily[dayKey] || {}).forEach(pointId => allPointIds.add(pointId));
    });

    debugLog('All point IDs collected', {
        totalPoints: allPointIds.size,
        pointIds: Array.from(allPointIds).slice(0, 3)
    });

    // 1. 更新Daily维度（只处理当天数据）
    if (!stats.byTimeDimension.daily) {
        stats.byTimeDimension.daily = {};
    }
    
    if (hasCurrentDayData) {
        stats.byTimeDimension.daily[currentDay] = {};
        Object.entries(stats.byMeasurementPoint || {}).forEach(([pointId, pointData]) => {
            if (pointData && pointData.history && pointData.history.length > 0) {
                const dayHistory = pointData.history.filter(record => 
                    record.timestamp.startsWith(currentDay)
                );
                
                if (dayHistory.length > 0) {
                    stats.byTimeDimension.daily[currentDay][pointId] = calculateConsumption(dayHistory);
                }
            }
        });
    }

    // 2. 更新Monthly维度（近30天滚动窗口，基于Daily数据）
    if (!stats.byTimeDimension.monthly) {
        stats.byTimeDimension.monthly = {};
    }
    stats.byTimeDimension.monthly[currentDay] = {};
    
    Array.from(allPointIds).forEach(pointId => {
        stats.byTimeDimension.monthly[currentDay][pointId] = 
            calculateRollingWindowFromDaily(stats, pointId, 30, currentDate);
    });

    // 3. 更新Weekly维度（近7天滚动窗口，基于Daily数据）
    if (!stats.byTimeDimension.weekly) {
        stats.byTimeDimension.weekly = {};
    }
    stats.byTimeDimension.weekly[currentDay] = {};
    
    Array.from(allPointIds).forEach(pointId => {
        stats.byTimeDimension.weekly[currentDay][pointId] = 
            calculateRollingWindowFromDaily(stats, pointId, 7, currentDate);
    });

    // 4. 更新Yearly维度（近12个月，基于Monthly数据）
    if (!stats.byTimeDimension.yearly) {
        stats.byTimeDimension.yearly = {};
    }
    
    const last12Months = getLast12Months(currentDate);
    
    debugLog('Processing yearly dimension based on monthly data', {
        currentMonth: currentMonth,
        last12Months: last12Months,
        totalPoints: allPointIds.size,
        availableMonthlyKeys: Object.keys(stats.byTimeDimension.monthly)
    });
    
    // 为每个月计算月度汇总（基于Monthly数据）
    last12Months.forEach(monthKey => {
        if (!stats.byTimeDimension.yearly[monthKey]) {
            stats.byTimeDimension.yearly[monthKey] = {};
        }
        
        Array.from(allPointIds).forEach(pointId => {
            stats.byTimeDimension.yearly[monthKey][pointId] = 
                calculateMonthlyAggregationFromMonthly(stats, pointId, monthKey, currentDate);
        });
    });

    // 5. 清理过期数据
    function cleanExpiredData() {
        const beforeCleanup = {
            daily: Object.keys(stats.byTimeDimension.daily),
            weekly: Object.keys(stats.byTimeDimension.weekly),
            monthly: Object.keys(stats.byTimeDimension.monthly),
            yearly: Object.keys(stats.byTimeDimension.yearly)
        };

        // 清理Daily数据（只保留当天）
        Object.keys(stats.byTimeDimension.daily).forEach(day => {
            if (day !== currentDay) {
                delete stats.byTimeDimension.daily[day];
            }
        });

        // 清理Weekly数据（保留最近7天）
        const weekStart = new Date(currentDate);
        weekStart.setDate(weekStart.getDate() - 6);
        const weekStartStr = formatDate(weekStart);
        Object.keys(stats.byTimeDimension.weekly).forEach(day => {
            if (day < weekStartStr) {
                delete stats.byTimeDimension.weekly[day];
            }
        });

        // 清理Monthly数据（保留最近30天 - 关键！）
        const monthStart = new Date(currentDate);
        monthStart.setDate(monthStart.getDate() - 29);
        const monthStartStr = formatDate(monthStart);
        Object.keys(stats.byTimeDimension.monthly).forEach(day => {
            if (day < monthStartStr) {
                delete stats.byTimeDimension.monthly[day];
            }
        });

        // 清理Yearly数据（保留最近12个月）
        const validMonths = new Set(last12Months);
        Object.keys(stats.byTimeDimension.yearly).forEach(month => {
            if (!validMonths.has(month)) {
                delete stats.byTimeDimension.yearly[month];
            }
        });

        const afterCleanup = {
            daily: Object.keys(stats.byTimeDimension.daily),
            weekly: Object.keys(stats.byTimeDimension.weekly),
            monthly: Object.keys(stats.byTimeDimension.monthly),
            yearly: Object.keys(stats.byTimeDimension.yearly)
        };

        debugLog('Data cleanup completed', {
            before: beforeCleanup,
            after: afterCleanup
        });
    }

    // 执行清理
    cleanExpiredData();

    // 更新最后更新时间
    stats.lastUpdated = getCurrentTimestamp().toISOString();

    // 保存结果
    global.set('_ELECTRIC_STATISTICS_', stats);

    // 生成详细报告
    const samplePointId = Array.from(allPointIds)[0];
    let finalReport = {
        timestamp: stats.lastUpdated,
        currentDay: currentDay,
        currentMonth: currentMonth,
        dimensions: {
            daily: {
                keys: Object.keys(stats.byTimeDimension.daily),
                count: Object.keys(stats.byTimeDimension.daily).length
            },
            weekly: {
                keys: Object.keys(stats.byTimeDimension.weekly),
                count: Object.keys(stats.byTimeDimension.weekly).length
            },
            monthly: {
                keys: Object.keys(stats.byTimeDimension.monthly),
                count: Object.keys(stats.byTimeDimension.monthly).length
            },
            yearly: {
                keys: Object.keys(stats.byTimeDimension.yearly).sort(),
                count: Object.keys(stats.byTimeDimension.yearly).length,
                expectedMonths: last12Months
            }
        },
        totalPoints: allPointIds.size
    };
    
    if (samplePointId) {
        finalReport.sampleCalculation = {
            pointId: samplePointId,
            daily: stats.byTimeDimension.daily[currentDay]?.[samplePointId] || null,
            weekly: stats.byTimeDimension.weekly[currentDay]?.[samplePointId] || null,
            monthly: stats.byTimeDimension.monthly[currentDay]?.[samplePointId] || null,
            yearly: stats.byTimeDimension.yearly[currentMonth]?.[samplePointId] || null
        };
    }

    debugLog('Redesigned aggregation completed', finalReport);

} catch (error) {
    node.error("Error in redesigned aggregation: " + error.message);
    node.warn(error.stack);
}

return msg;